#pragma once
#include <vector>
#include <queue>
#include <string>
#include <functional>
#include <pthread.h>
#include "Pthread.hpp"
#include "Log.hpp"
#include "LockGuard.hpp"

using namespace my;
using namespace log_ns;

static const int THREADNUM = 5;

void test(const std::string &name)
{
    LOG(DEBUG, "%s test success\n", name.c_str());
}

template <class T>
class ThreadPool
{
private:
    void Lock()
    {
        pthread_mutex_lock(&_mutex);
    }

    void Unlock()
    {
        pthread_mutex_unlock(&_mutex);
    }

    void Sleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }

    void Wakeup()
    {
        pthread_cond_signal(&_cond);
    }

    void WakeupAll()
    {
        pthread_cond_broadcast(&_cond);
    }

    bool IsEmpty()
    {
        return _taskQueue.empty();
    }

    void HandlerTask(const std::string &name)
    {
        while (true)
        {
            Lock();
            while (IsEmpty() && _isRunning)
            {
                ++_sleepThreadNum;
                LOG(INFO, "%s sleep\n", name.c_str());
                Sleep();
                LOG(INFO, "%s wakeup\n", name.c_str());
                --_sleepThreadNum;
            }

            if (IsEmpty() && !_isRunning) //?
            {
                Unlock();
                LOG(INFO, "%s quit", name.c_str());
                break;
            }

            T t = _taskQueue.front();
            _taskQueue.pop();
            Unlock();

            t();
        }
    }

    ThreadPool() : _threadNum(THREADNUM), _isRunning(false), _sleepThreadNum(0)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }

    void Init()
    {
        func_t func = std::bind(&ThreadPool::HandlerTask, this, std::placeholders::_1);
        for (int i = 0; i < _threadNum; ++i)
        {
            std::string threadName = "thread-" + std::to_string(i + 1);
            // _threads.emplace_back(threadName, test);
            _threads.emplace_back(threadName, func);
            // _threads.push_back(Thread(threadName, test));
            LOG(INFO, "%s, init done\n", threadName.c_str());
        }
    }

    void Start()
    {
        _isRunning = true;
        for (auto &thread : _threads)
        {
            thread.Start();
        }
    }

    ThreadPool(const ThreadPool<T> &) = delete;
    void operator=(const ThreadPool<T> &) = delete;

public:
    static ThreadPool<T> *GetInstance()
    {
        if (_tp == nullptr)
        {
            LockGuard lockGuard(&_sigMutex);
            if (_tp == nullptr)
            {
                _tp = new ThreadPool();
                _tp->Init();
                _tp->Start();
                LOG(INFO, "creat ThreadPool\n");
            }
            else
            {
                LOG(INFO, "get ThreadPool\n");
            }
        }
        return _tp;
    }
    void Stop()
    {
        Lock();
        _isRunning = false;
        WakeupAll();
        Unlock();
        LOG(INFO, "ThreadPool quit\n");
    }

    void Equeue(const T &in)
    {
        Lock();
        if (_isRunning)
        {
            _taskQueue.push(in);
            if (_sleepThreadNum > 0)
                Wakeup();
        }
        Unlock();
    }

    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

private:
    int _threadNum;
    std::vector<Thread> _threads;
    std::queue<T> _taskQueue;
    bool _isRunning;
    int _sleepThreadNum;

    pthread_mutex_t _mutex;
    pthread_cond_t _cond;

    static ThreadPool<T> *_tp;
    static pthread_mutex_t _sigMutex;
};

template <class T>
ThreadPool<T> *ThreadPool<T>::_tp = nullptr;
template <class T>
pthread_mutex_t ThreadPool<T>::_sigMutex = PTHREAD_MUTEX_INITIALIZER;